#include "primitives.h"

bool Primitive::intersectShadow(const Ray& ray)
{
	Vector3 tv, tn;
	return intersect(ray, tv, tn);
}

AABB Sphere::getAABB()
{
	// TODO
	return AABB();
}

bool Sphere::intersect(const Ray& ray, 
		Vector3& point, Vector3& normal)
{
	Ray r = ray;
	r.dir.normalize();

	Vector3 v = r.orig - center;
	
	// float a = 1.0f
	float b = Vector3::dot(v * 2.0f, r.dir);
	float c = Vector3::dot(v, v) - radius * radius;

	float d = b*b - 4.0f * c;

	if(d < 0.0f)
		return false;

	float t1 = (-b + sqrt(d)) / 2.0f;
	float t2 = (-b - sqrt(d)) / 2.0f;

	float t = min(t1, t2);

	if(t < 0.0f)
	{
		if(max(t1, t2) < 0.0f)
			return false;
		else
			t = max(t1, t2);
	}

	if(eql(t, 0.0f))
		return false;

	point = r.orig + r.dir * t;
	normal = point - center;
	normal.normalize();

	return true;
}
